package com.business.business.web.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.business.business.common.base.BaseService;
import com.business.business.model.Business;
import com.business.business.model.EmergencyCommand;
import com.business.business.model.EmgPlace;
import com.business.business.support.model.RespEntity;
import com.business.business.support.utils.https.StringUtil;
import com.business.business.support.utils.requestutil.HttpRequestUtil;
import com.business.business.web.mapper.BusinessMapper;
import com.business.business.web.mapper.EmergencyCommandMapper;
import com.business.business.model.Organization;
import com.business.business.web.mapper.OrganizationMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: YangYu
 * @ClassName: EmergencyCommand
 * @Date: Created in 10:00 2024/4/27
 * @Description: 应急指挥
 */
@Service
public class EmergencyCommandService extends BaseService {

    @Resource
    private EmergencyCommandMapper emergencyCommandMapper;
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private OrganizationMapper organizationMapper;

    /**
     * @Author YangYu
     * @Description 应急指挥信息新增、编辑
     * @Date Created in 10:05 2024/4/27
     * @Param [jsonParam]
     */

    public RespEntity addOrUpdate(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        EmergencyCommand emergencyCommand = jsonParam.toBean(EmergencyCommand.class);
        if (userType.equals("1")) {
            //机构详情
            Organization organization = organizationMapper.getOrganization(homeId);
            emergencyCommand.setOrgIds(organization.getAllId());
            if (StrUtil.isNotBlank(emergencyCommand.getBusinessId())) {
                Business business = businessMapper.selectById(emergencyCommand.getBusinessId());
                emergencyCommand.setArea(business.getArea());
                emergencyCommand.setAreaName(business.getAreaName());
            }
        } else {
            Business business = businessMapper.selectById(homeId);
            emergencyCommand.setOrgIds(business.getOrgIds());
            emergencyCommand.setArea(business.getArea());
            emergencyCommand.setAreaName(business.getAreaName());
        }
        if (StringUtil.strIsNullOrEmpty(emergencyCommand.getId())) {
            // 为空，新增
            emergencyCommand.setId(UUID.randomUUID().toString());
            emergencyCommandMapper.insert(emergencyCommand);
        } else {
            emergencyCommandMapper.updateById(emergencyCommand);
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 应急指挥信息删除
     * @Date Created in 10:05 2024/4/27
     * @Param [jsonParam]
     */

    public RespEntity emergencyCommandDel(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isNotBlank(jsonParam.getStr("id"))){
            emergencyCommandMapper.deleteById(jsonParam.getStr("id"));
        }else {
            return RespEntity.fail("ID不能为空");
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 应急指挥信息分页列表
     * @Date Created in 10:05 2024/4/27
     * @Param [jsonParam]
     */

    public RespEntity emergencyCommandListPage(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        //页数
        Integer page = jsonParam.getInt("page");
        //条
        Integer limit = jsonParam.getInt("limit");
        Page<EmergencyCommand> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<EmergencyCommand> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.like(jsonParam.containsKey("name"), EmergencyCommand::getName, jsonParam.getStr("name"))
                .like(userType.equals("1"),EmergencyCommand::getOrgIds, homeId)
                .like(jsonParam.containsKey("area"),EmergencyCommand::getArea, jsonParam.getStr("area"))
                .eq(jsonParam.containsKey("type"),EmergencyCommand::getType,jsonParam.getInt("type"))
                .like(jsonParam.containsKey("businessId"),EmergencyCommand::getBusinessId, jsonParam.getStr("businessId"));
        IPage<EmergencyCommand> iPage = emergencyCommandMapper.selectPage(pageInfo, lambdaQuery);
        return RespEntity.success(iPage);
    }

    /**
     * @Author YangYu
     * @Description 应急保障情况（数量）
     * @Date Created in 10:05 2024/4/27
     * @Param [jsonParam]
     */

    public RespEntity emergencyCommandCount(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        QueryWrapper<EmergencyCommand> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("type","COUNT(type) as count")
                .like("org_ids",homeId)
                .like(jsonParam.containsKey("area"),"area",jsonParam.getStr("area"))
                .groupBy("type")
                .orderByDesc("count");
        List<EmergencyCommand> emergencyCommandList = emergencyCommandMapper.selectList(queryWrapper);

        int placeNumber = 0;
        int material = 0;
        int proNumber = 0;
        int teamNumber = 0;
        int fireStation = 0;
        for (EmergencyCommand emergencyCommand : emergencyCommandList){
            if (emergencyCommand.getType() == 1){
                placeNumber = emergencyCommand.getCount();
            }else if (emergencyCommand.getType() == 2){
                material = emergencyCommand.getCount();
            }else if (emergencyCommand.getType() == 3){
                proNumber = emergencyCommand.getCount();
            }else if (emergencyCommand.getType() == 4){
                teamNumber = emergencyCommand.getCount();
            }else if (emergencyCommand.getType() == 5){
                fireStation = emergencyCommand.getCount();
            }
        }
        Map<String, Object> map = new HashMap<>();
        // 场所数量
        map.put("placeNumber", placeNumber);
        // 物资总数量
        map.put("material", material);
        // 专家数量
        map.put("proNumber", proNumber);
        // 队伍数量
        map.put("teamNumber", teamNumber);
        // 微型消防站
        map.put("fireStation", fireStation);
        return RespEntity.success(map);
    }

    /**
     * @Author YangYu
     * @Description 应急指挥信息列表
     * @Date Created in 10:05 2024/4/27
     * @Param [jsonParam]
     */

    public RespEntity emergencyCommandList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        QueryWrapper<EmergencyCommand> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("org_ids",homeId)
                .eq(jsonParam.containsKey("type"),"type",jsonParam.getInt("type"))
                .like(jsonParam.containsKey("area"),"area",jsonParam.getStr("area"));
        List<EmergencyCommand> emergencyCommandList = emergencyCommandMapper.selectList(queryWrapper);
        return RespEntity.success(emergencyCommandList);
    }
}
